﻿
namespace Sai.Core
{
    using System;
    using System.Runtime.InteropServices;
    using System.Text;

    public static class PathExtensions
    {
        public static string PathRelativeTo(this string absolutePath, string relativeTo)
        {
            StringBuilder builder = new StringBuilder(Native.MAX_PATH);
            UInt32 dwAttrFrom = Native.FILE_ATTRIBUTE_DIRECTORY;
            UInt32 dwAttrTo = 0;

            if (Native.PathRelativePathTo(
                 builder,
                 relativeTo,
                 dwAttrFrom,
                 absolutePath,
                 dwAttrTo))
            {
                return builder.ToString();
            }

            return absolutePath;
        }

    }

    internal sealed class Native
    {
        public const UInt32 FILE_ATTRIBUTE_DIRECTORY = 0x10;
        public const Int32 MAX_PATH = 260;

        [DllImport("shlwapi.dll", CharSet = CharSet.Auto)]
        internal static extern bool PathRelativePathTo(
             [Out] StringBuilder pszPath,
             [In] string pszFrom,
             [In] uint dwAttrFrom,
             [In] string pszTo,
             [In] uint dwAttrTo
        );
    }
}
